package cn.tedu.yxc;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//@WebFilter(urlPatterns = "/Yxc/*")
public class CoreFilter implements Filter {
    // 销毁函数，被 tomcat 被停止的时候触发
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException, IOException, ServletException {
        // 获取请求对象
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        // 获取被拦截的地址
        String uri = request.getRequestURI();
        if ("/Yxc/login.jsp".equals(uri) || uri.startsWith("/Yxc/assets") ) {
            // 通行
            chain.doFilter(req, resp);
            return;
        }

        // 获取会话对象
        HttpSession session = request.getSession();
        Object uid = session.getAttribute("UID");
        if (uid == null) {
            // 如果 uid 为 null，则说明没有保存用户的信息，视作没登陆
            response.sendRedirect("/Yxc/login.jsp");
            return;
        }

        // 如果调用了 doFilter 则说明通行，否则不允许通行
        chain.doFilter(req, resp);
    }

    // 初始化函数，在启动的时候触发
    public void init(FilterConfig config) throws ServletException {
    }
}
